var resultData = null;

$(function(){
	console.log(GetRequest());
	var user = JSON.parse(GetRequest().param).user;
	var deptAccountID = JSON.parse(GetRequest().param).InDeptAccountID;
	$("#breadcrumb").html(JSON.parse(GetRequest().param).breadcrumb)
	
  layui.use(['laydate', 'form', 'table','laytpl'], function () {
    var laydate = layui.laydate,
      form = layui.form,
      table = layui.table;
    //渲染时间插件
    laydate.render({
      elem: '#startTime'
      , showBottom: false,
    })
    laydate.render({
      elem: '#endTime'
      , showBottom: false
    })
    $(document).ready(function(){
    	$("#startTime").val("");
		$("#endTime").val("");
		$("#roomname").val("");
		$("#status").val("2");
    	
    	queryData(deptAccountID)
    	console.log(resultData)
    	
	      table.render({
	        elem: '#roomTable'
	        , height: 'full-200'
	        ,data:resultData
	        , cols: [[ //表头
	          {field: 'RoomCode', title: '房间编号',templet:'<div><span title="{{d.RoomCode}}">{{d.RoomCode}}</span></div>',width:160}
	          , {field: 'RoomName', title: '房间名称',edit:"text",templet:'<div><span title="{{d.RoomName}}">{{d.RoomName}}</span></div>',width:160}
	          , {field: 'Status', title: '状态',width:100}
	          , {field: 'InputUserName', title: '录入人',width:120}
	          , {field: 'InputTime', title: '录入时间',width:160,templet:'<div><span title="{{d.InputTime}}">{{d.InputTime==null||d.InputTime==undefined?"":d.InputTime}}</span></div>'}
	          , {field: 'UpdateUserName', title: '修改人',width:120 }
	          , {field: 'UpdateTime', title: '修改时间',width:160,templet:'<div><span title="{{d.UpdateTime}}">{{d.UpdateTime==null||d.UpdateTime==undefined?"":d.UpdateTime}}</span></div>' }
	          ,{title: '操作', align:'center',toolbar: '#bar'}
	        ]]
	        //隐藏了列
	        ,done: function(res, curr, count) {
        		$(".layui-table-main table tbody").append('<tr><td></td><td><input style="width:110px;" class="layui-input" type="text" id="new"></td><td></td><td></td><td></td><td></td><td></td><td data-field="8" align="center" data-off="true"><div class="layui-table-cell laytable-cell-1-8"> <a id="saveNew">保存</a></div></td></tr>')
	        }
	      })
	      
	      if(resultData.length == 0){
	    	  reloadPageTableWithNoData();
	      }
  
	      //查询按钮的事件，以及查询的参数
	    form.on('submit(search)', function (data) {
	//      console.log($(data.form).serialize());
	    	queryData(deptAccountID);
	    	if(resultData.length == 0){
	    		reloadPageTableWithNoData();
	    	}else{
	    		reloadPageTable();
	    	}
	    	
	      return false;//必须写
	    });
	  //返回按钮绑定事件
	    $("#back").click(function() {
	    	parent.showMenuFn();
			parent.$('#main').empty();
	    })
      
      table.on('tool(roomTable)', function(obj){
        var data = obj.data;
        console.log(data);
        var layEvent = obj.event;
        if(layEvent === 'save'){
        	var text=$("#new").val();
            var savedata = {
    		  "ID" : null,
    		  "RoomID" : "",
    		  "RoomCode" : "",
    		  "RoomName" : text,
    		  "DeptAccountID" : deptAccountID,
    		  "InputUser" : user.Ygid,
    		  "InputTime" : "",
    		  "UpdateUser" : "",
    		  "UpdateTime" : ""
    	     }
            var params = {
    			className : 'TwoLevelStockManager',
    			method : 'InputRoomsToDept',
    			roomsToDeptInfo : JSON.stringify(savedata),
    			userID : user.Ygid
    		}
            $.ajax({
    			type : "post",
    			url : getRootPath() + 'api/sendPostRequest',
    			dataType : "json",
    			contentType: 'application/json',
    			data : JSON.stringify(params),
    			async : false,
    			success : function(data) {
    				if(data.issuccess == "0"){
    					layer.msg('保存成功！',{time:1000});
    					console.log(data.result)
    					
    					$("#startTime").val("");
						$("#endTime").val("");
						$("#roomname").val("");
						$("#status").val("2");
    					
    					queryData(deptAccountID);
    					reloadPageTable();
    				} else{
    					layer.msg('保存失败！',{time:1000});
    				}
    			},
    			error : function(data) {
    				console.log(data.message)
    			}
    		})
        } else if(layEvent === 'del'){ //删除
          layer.confirm('真的删除行么', function(index){
            
            if(data.ID!=null){
//              向服务端发送删除指令
                var params = {
    				className : 'TwoLevelStockManager',
    				method : 'DeleteRoomsToDept',
    				id : data.ID
    			}
            	$.ajax({
        			type : "post",
        			url : getRootPath() + 'api/sendPostRequest',
        			dataType : "json",
        			contentType: 'application/json',
        			data : JSON.stringify(params),
        			async : false,
        			success : function(data) {
        				if(data.issuccess == "0"){
        					obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        					layer.close(index);
        					
        					layer.msg('删除成功！',{time:1000});
        					$("#startTime").val("");
        					$("#endTime").val("");
        					$("#roomname").val("");
        					$("#status").val("2");
        					
        					queryData(deptAccountID);
        					if(resultData.length == 0){
        						reloadPageTableWithNoData();
        					}else{
        						reloadPageTable();
        					}
        				} else{
        					layer.msg('删除失败！',{time:1000});
        				}
        			},
        			error : function(data) {
        				console.log(data.message)
        			}
        		})
            } else{
            	obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
				layer.close(index);
				layer.msg('删除成功！',{time:1000});
            }
          });
        } else if(layEvent === 'edit'){ //修改
        	var savedata = {
			  "ID" : data.ID,
			  "RoomID" : data.RoomID,
			  "RoomCode" : data.RoomCode,
			  "RoomName" : data.RoomName,
			  "DeptAccountID" : deptAccountID,
			  "InputUser" : data.InputUser,
			  "InputTime" : new Date(data.InputTime).format("yyyy-MM-dd hh:mm:ss"),
			  "UpdateUser" : data.UpdateUser,
			  "UpdateTime" : ""
		     }
	        var params = {
				className : 'TwoLevelStockManager',
				method : 'ModifyRoomsToDept',
				roomsToDeptInfo : JSON.stringify(savedata),
				userID : user.Ygid
			}
	        $.ajax({
				type : "post",
				url : getRootPath() + 'api/sendPostRequest',
				dataType : "json",
				contentType: 'application/json',
				data : JSON.stringify(params),
				async : false,
				success : function(data) {
					if (data.issuccess == 0) {
						layer.msg('保存成功！',{time:1000});
						console.log(data.result)
						queryData(deptAccountID);
				    	table.reload("roomTable",{
				    		data:resultData
				    	})
					} else {
						layer.msg('保存失败！',{time:1000});
					}
					
				},
				error : function(data) {
					console.log(data.message)
				}
			})
        }else if(layEvent === 'stop'){//停用
        	if(data.Status == ""||data.Status == null||data.Status == undefined){
      		  layer.msg('数据未保存,无法进行此操作',{time:2000});
      		  return;
      	  }
        	var params = {
    				className : 'TwoLevelStockManager',
    				method : 'UpdateRoomsToDeptStatus',
    				id : data.ID,
    				status : "0"
    			}
            	$.ajax({
        			type : "post",
        			url : getRootPath() + 'api/sendPostRequest',
        			dataType : "json",
        			contentType: 'application/json',
        			data : JSON.stringify(params),
        			async : false,
        			success : function(data) {
        				if (data.issuccess == 0) {
        					layer.msg('已停用！',{time:1000});
            				console.log(data.result)
            				queryData(deptAccountID);
        			    	table.reload("roomTable",{
        			    		data:resultData
        			    	})
        				}else {
        					layer.msg('停用失败！',{time:1000});
        				}
        				
        			},
        			error : function(data) {
        				console.log(data.message)
        			}
        		})
        }else if(layEvent === 'start'){//启用
        	if(data.Status == ""||data.Status == null||data.Status == undefined){
      		  layer.msg('数据未保存,无法进行此操作',{time:2000});
      		  return;
      	  }
        	var params = {
				className : 'TwoLevelStockManager',
				method : 'UpdateRoomsToDeptStatus',
				id : data.ID,
				status : "1"
			}
        	$.ajax({
    			type : "post",
    			url : getRootPath() + 'api/sendPostRequest',
    			dataType : "json",
    			contentType: 'application/json',
    			data : JSON.stringify(params),
    			async : false,
    			success : function(data) {
    				if (data.issuccess == 0) {
    					layer.msg('已启用！',{time:1000});
        				console.log(data.result)
        				queryData(deptAccountID);
    			    	table.reload("roomTable",{
    			    		data:resultData
    			    	})
    				}else{
    					layer.msg('启用失败！',{time:1000});
    				}
    			},
    			error : function(data) {
    				console.log(data.message)
    			}
    		})
        }
      });
      
      $("body").on("click","#saveNew",function () {
        var text=$("#new").val();
        var savedata = {
		  "ID" : null,
		  "RoomID" : "",
		  "RoomCode" : "",
		  "RoomName" : text,
		  "DeptAccountID" : deptAccountID,
		  "InputUser" : user.Ygid,
		  "InputTime" : "",
		  "UpdateUser" : "",
		  "UpdateTime" : ""
	     }
        var params = {
			className : 'TwoLevelStockManager',
			method : 'InputRoomsToDept',
			roomsToDeptInfo : JSON.stringify(savedata),
			userID : user.Ygid
		}
        $.ajax({
			type : "post",
			url : getRootPath() + 'api/sendPostRequest',
			dataType : "json",
			contentType: 'application/json',
			data : JSON.stringify(params),
			async : false,
			success : function(data) {
				if(data.issuccess == "0"){
					layer.msg('保存成功！',{time:1000});
					console.log(data.result)
					
					$("#startTime").val("");
					$("#endTime").val("");
					$("#roomname").val("");
					$("#status").val("2");
					
					queryData(deptAccountID);
					reloadPageTable();
				}else{
					layer.msg('保存失败！',{time:1000});
				}
			},
			error : function(data) {
				console.log(data.message)
			}
		})
      })
      function reloadPageTableWithNoData(){
    	  table.reload("roomTable",{
    		  data:[{"RoomCode":"","RoomName":"","Status":"","InputUserName":"","InputTime":"","UpdateUserName":"","UpdateTime":""}],
    		  cols: [[ //表头
    			  {field: 'RoomCode', title: '房间编号',width:160}
    			  , {field: 'RoomName', title: '房间名称',edit:"",templet:'#input',width:160}
    			  , {field: 'Status', title: '状态',width:100}
    			  , {field: 'InputUserName', title: '录入人',width:120}
    			  , {field: 'InputTime', title: '录入时间',width:160}
    			  , {field: 'UpdateUserName', title: '修改人',width:120 }
    			  , {field: 'UpdateTime', title: '修改时间',width:160 }
    			  ,{title: '操作', align:'center',toolbar: '#bar1'}
    			  ]],
    			  done: function(res, curr, count) {
    				  
    			  }
    	  })
      }
      
      function reloadPageTable(){
    	  table.reload("roomTable",{
    		  data:resultData,
    		  cols: [[ //表头
    			  {field: 'RoomCode', title: '房间编号',templet:'<div><span title="{{d.RoomCode}}">{{d.RoomCode}}</span></div>',width:160}
    			  , {field: 'RoomName', title: '房间名称',edit:"text",templet:'<div><span title="{{d.RoomName}}">{{d.RoomName}}</span></div>',width:160}
    			  , {field: 'Status', title: '状态',width:100}
    			  , {field: 'InputUserName', title: '录入人',width:120}
    			  , {field: 'InputTime', title: '录入时间',width:160}
    			  , {field: 'UpdateUserName', title: '修改人',width:120 }
    			  , {field: 'UpdateTime', title: '修改时间',width:160 }
    			  ,{title: '操作', align:'center',toolbar: '#bar'}
    			  ]],
    			  done: function(res, curr, count) {
    				  $(".layui-table-main table tbody").append('<tr><td></td><td><input style="width:110px;" class="layui-input" type="text" id="new"></td><td></td><td></td><td></td><td></td><td></td><td data-field="8" align="center" data-off="true"><div class="layui-table-cell laytable-cell-1-8"> <a id="saveNew">保存</a></div></td></tr>')
    			  }
    	  })
      }
    })
  })
})

/**
 * 查询数据
 */
function queryData(deptAccountID) {
	var condition = {
		"Conditions" : [ {
			"ColumnName" : "RoomName",
			"FullString" : null,
			"Oper" : "Like",
			"Value" : "%"+$("#roomname").val()+"%",
			"Type" : "String"
		},{
			"ColumnName" : "DeptAccountID",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : deptAccountID,
			"Type" : "String"
		} ,{
			"ColumnName" : "a.yxbz",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : "1",
			"Type" : "String"
		} ],
		"Type" : "AND"
	};
	if($("#startTime").val()!=""){
		condition.Conditions.push({
			"ColumnName" : "InputTime",
			"FullString" : null,
			"Oper" : "MoreOrEqual",
			"Value" : $("#startTime").val(),
			"Type" : "DateTime"
		})
	}
	if ($("#endTime").val()!="") {
		condition.Conditions.push({
			"ColumnName" : "InputTime",
			"FullString" : null,
			"Oper" : "LessOrEqual",
			"Value" : $("#endTime").val()+" 23:59:59",
			"Type" : "DateTime"
		})
	}
	if ($("#status").val() != "2") {
		condition.Conditions.push({
			"ColumnName" : "Status",
			"FullString" : null,
			"Oper" : "Equal",
			"Value" : $("#status").val(),
			"Type" : "String"
		})
	}

	var params = {
		className : 'TwoLevelStockManager',
		method : 'GetRoomsToDepts',
		condition : JSON.stringify(condition),
	}
	$.ajax({
		type : "post",
		url : getRootPath() + 'api/sendPostRequest',
		dataType : "json",
		contentType : 'application/json',
		data : JSON.stringify(params),
		async : false,
		success : function(data) {
			console.log(data.result)
			
			if (data.issuccess == 0) {
				resultData = JSON.parse(data.result);
				for(var i=0;i<resultData.length;i++){
					if(resultData[i].InputTime==null){
						resultData[i].InputTime = "";
					}
					if(resultData[i].UpdateTime==null){
						resultData[i].UpdateTime = "";
					}
					if(resultData[i].Status){
						resultData[i].Status = "启用";
					} else {
						resultData[i].Status = "停用";
					}
				}
			}else{
				layer.msg('查询失败！',{time:3000});
			}
		},
		error : function(data) {
			console.log(data.message)
		}
	})
}

